<?php
require_once dirname(__FILE__) . '/ServiceBase.php';
/**
 * Protect Service （工作流）
 *
 */
class SDOEsb extends ServiceBase
{
    # ESB服务地址
    const ESB_URL = 'ESB_URL';
//    const PRE_ESB_URL = 'PRE_ESB_URL';
    # ESB API VERSION
    const ESB_API_VERSION = "1.0";
    # ESB API_KEY
    const ESB_API_KEY = "100000000";
    # ESB CONFIG NAME
    const ESB_CONFIG_NAME ="ESB_CONFIG"; 
    # ESB CONFIG NAME PRE
    const PRE_ESB_CONFIG_NAME ="PRE_ESB_CONFIG"; 
    /**
     * 发送ESB请求
     *
     * @param string $message 
     * @param string  $service 服务
     * @param string $method 方法
     * @param array $params
     * @param string $env
     * @return mixed
     */
    public static function esbRequest (&$message, $service, $subService=null, $method, $params, $env = SDK_ENV_TEST)
    {
        /*$url = ($env === SDK_ENV_TEST) ? sdk_fetch_config(SDK_ENV . self::PRE_ESB_URL) : sdk_fetch_config(
        SDK_ENV . self::ESB_URL);*/
        $url = sdk_fetch_config(SDK_ENV . self::ESB_URL)."{$service}";
        $configName = ($env === SDK_ENV_TEST) ? self::PRE_ESB_CONFIG_NAME : self::ESB_CONFIG_NAME;
        $key = SDK_ENV .$configName.".".$service;
        if ($subService) {
        	$key.=".".$subService;
        }
        $serviceConfig = sdk_fetch_config($key);
        $params = array_merge(array(
	        'api_key'=>self::ESB_API_KEY, 
	        'sdo_service'=>$serviceConfig['sdo_service'], 
	        'method'=>$method, 
	        'call_id'=>$_SERVER['REQUEST_TIME'], 
	        'v'=>self::ESB_API_VERSION
        ), $params);
        
        //print_r($param);
        $content = self::getRestfulContent(
        $url . '?' . strtr(http_build_query($params), array("&amp;"=>"&")), $message);
        $errMsg = array("method"=> $service , "params"=> json_encode($params) , "env"=>$env);
        if ($content === FALSE) {
            $errMsg["exception"] = $message;
            $errMsg["location"] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $errMsg["return"] = $content;
        $errMsg["location"] = $url;
        $result = self::processResult($content, $errMsg, $message);        
        return $result;
    }
    
    private static function processResult($content, $errMsg, &$message)
    {
    	$result = json_decode($content);
    	if (isset($result->success) ) {
    		if ($result->success==true) {
    			self::log($errMsg, __CLASS__, true);
    			return $result->result;
    		} 
    		$message = isset($result->error_message) ? $result->error_message : '接口错误';
            self::error($errMsg, __CLASS__);
            self::setErrNo(SDOServiceErrorCode::API_EC_COMMON_ERROR);
    		
    	} else {
    		self::fatal($errMsg, __CLASS__);
    		self::setErrNo(SDOServiceErrorCode::API_EC_SERVICE);
    	}
    	return false;
    } 
    
}
